package executor.impl;

import java.io.File;
import java.io.FileFilter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class FileCrawlingService extends ThreadPoolExecutor {
	private final ExecutorService fileCrawlingService;
	private final Object waitLock = new Object();

	public FileCrawlingService(ExecutorService fileCrawlingService) {
		super(1, 4, 1, TimeUnit.MINUTES, new PausableQueue(1000));
		this.fileCrawlingService = fileCrawlingService;
	}
	
	public void startCrawling(File root, FileFilter fileFilter, ExecutorService indexService) {
		fileCrawlingService.execute(new FileCrawler(root, fileFilter, indexService, this));
	}
	
	public void waitUntilEnd() {
		while (true) {
			PausableQueue pq = (PausableQueue)getQueue();
			pq.pause();
			if (getActiveCount() == 0 && pq.size() == 0)
				break;
			pq.resume();
			try {
				waitLock.wait(1);
			} catch (InterruptedException e) {
				break;
			}
		}
	}
}
